/**
 * 鉴权拦截器
 * @author: yupi
 */
import Taro from "@tarojs/taro"
import {getGlobalData} from "../../global.d"
import {authLogin} from "./service";
import {toast} from "../../utils";

// 鉴权级别
const AUTH_LEVEL = {
  USER: 'user', // 登录用户
  ADMIN: 'admin' // 管理员，最高权限
};

// 要拦截鉴权的url，对于操作（如“喜欢”），也当作url处理，规则为'/op/xxx'
const FILTER_URLS = {
  // '/pages/my/index': AUTH_LEVEL.USER,
  // [ops.doFavour]: AUTH_LEVEL.USER,
  '/pages/tools/uploadFiles/index':AUTH_LEVEL.ADMIN,
'/pages/tools/createHomework/index':AUTH_LEVEL.ADMIN,
'/pages/tools/createNotice/index':AUTH_LEVEL.ADMIN,

};

/**
 * 鉴权，根据页面所需的级别进行拦截
 * @param url
 * @param obj
 * @returns {Promise<boolean>}
 */
async function doAuth(url, obj) {
  const paramsIndex = url.indexOf('?');
  if (paramsIndex >= 0) {
    url = url.substring(0, paramsIndex);
  }
  const reqLevel = FILTER_URLS[url];
  // 必须授权登录才能访问，判断是否已授权
  let user = getGlobalData('user');
  if (user == null || user.userInfo == null) {
    // 是否已授权
    const authd = await Taro.getSetting().then(res => {
      return res.authSetting['scope.userInfo'];
    });
    if (!authd) {
      // 未授权，跳转到授权页
      doFilter('/pages/auth/index');
      return false;
    } else {
      // 已授权，直接登录
      user = await authLogin();
    }
  }
  const authLevel = user.userLastTimeClass.type
  switch (reqLevel) {
    case AUTH_LEVEL.ADMIN:
      if (authLevel !== AUTH_LEVEL.ADMIN) {
        toast('只有管理员可以访问哦');
        return false;
      }
      break;

  }
  if (obj) {
    obj.setState({
      user
    });
  }
  return true;
}

// 拦截，跳转到指定页面
function doFilter(url) {
  Taro.redirectTo({
    url
  });
}

export {
  AUTH_LEVEL,
  FILTER_URLS,
  doAuth
};

